package com.lzb.newloan.bqs;

import android.app.Activity;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.lzb.newloan.R;

import org.json.JSONObject;

import java.net.URLEncoder;

/**
 * Desction:
 * Author:Jianbo.Peng
 * Date:2017/5/24 上午11:28
 */
public class AgreementDialog extends Dialog implements View.OnClickListener{

    WebView webView;
    Button btnCancel;
    Button btnOk;

    String authagreementUrl = Datas.API_HOST + "common/authagreement";
    String getagreementUrl = Datas.API_HOST + "common/getagreement";
    private String isAuthTimeKey;
    private int serviceId;
    private Activity activity;
    private boolean isAuth;
    private CatLoadingView loadingView;

    public AgreementDialog(@NonNull Activity activity, int serviceId) {
        super(activity);
        this.activity = activity;
        this.serviceId = serviceId;
        if(Datas.DEBUG){
            authagreementUrl = Datas.API_HOST_DEV + "common/authagreement";
            getagreementUrl = Datas.API_HOST_DEV + "common/getagreement";
        }
        isAuthTimeKey = "isAuthTime_" + serviceId + Datas.params.getPartnerId() + Datas.params.getCertNo() + Datas.params.getMobile() + Datas.params.getName();
        long lastTime = AppCacheUtils.getInstance(activity).getLong(isAuthTimeKey, 0L);
        long curTime = System.currentTimeMillis();
        if(lastTime != 0 && (curTime - lastTime) < 172800000){
            isAuth = true;
        }

        loadingView = new CatLoadingView(activity);
    }

    /**
     * 获取手机大小（分辨率）
     *
     * @param activity
     * @return
     */
    private DisplayMetrics getScreenPix(Activity activity) {
        // DisplayMetrics 一个描述普通显示信息的结构，例如显示大小、密度、字体尺寸
        DisplayMetrics displaysMetrics = new DisplayMetrics();
        // 获取手机窗口的Display 来初始化DisplayMetrics 对象
        // getManager()获取显示定制窗口的管理器。
        // 获取默认显示Display对象
        // 通过Display 对象的数据来初始化一个DisplayMetrics 对象
        activity.getWindowManager().getDefaultDisplay()
                .getMetrics(displaysMetrics);
        return displaysMetrics;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
        WindowManager.LayoutParams.FLAG_BLUR_BEHIND);

        setContentView(R.layout.dialog_agreement);
        int height = getScreenPix(activity).heightPixels/4*3;
        LinearLayout llRoot = (LinearLayout)findViewById(R.id.ll_root);
        llRoot.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, height));

        webView = (WebView)findViewById(R.id.webview);
        btnCancel = (Button)findViewById(R.id.btn_cancel);
        btnOk = (Button)findViewById(R.id.btn_ok);
        btnCancel.setOnClickListener(this);
        btnOk.setOnClickListener(this);

        //设置编码
        webView.getSettings().setDefaultTextEncodingName("UTF-8");
        //设置是否支持javascript
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        //放大缩小
        webView.getSettings().setSupportZoom(true);
        //任意比例缩放
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setBuiltInZoomControls(true);
        //设置WebView使用广泛的视窗
        webView.getSettings().setLoadWithOverviewMode(true);
//        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);
        try {
            String name = URLEncoder.encode(Datas.params.getName(), "UTF-8");
            getagreementUrl += "?mobile=" + Datas.params.getMobile() + "&certNo=" + Datas.params.getCertNo() + "&name=" + name +"&partnerId=" + Datas.params.getPartnerId();
        }catch (Exception e){
            e.printStackTrace();
        }
        setCanceledOnTouchOutside(false);
        setCancelable(false);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id){
            case R.id.btn_ok:
                authagreement(serviceId);
                break;
            default:
                if(activity != null && !activity.isFinishing()) {
                    activity.finish();
                }
                dismiss();
                break;

        }
    }

    public void ifShow() {
        if(isAuth){
            return;
        }
        show();
        webView.loadUrl(getagreementUrl);

    }


    private void authagreement(final int serviceId){
        loadingView.show();
        AsyncTask task = new AsyncTask<Object, Void, String>(){

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                System.out.println("sssss11111" );
            }

            @Override
            protected String doInBackground(Object... voids) {
                String msg = "网络似乎有点问题";
                System.out.println("sssss1222222" );
                try {
                    com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
                    jsonObject.put("partnerId", Datas.params.getPartnerId());
                    jsonObject.put("mobile", Datas.params.getMobile());
                    jsonObject.put("certNo", Datas.params.getCertNo());
                    jsonObject.put("name", Datas.params.getName());
                    jsonObject.put("serviceId", serviceId);
                    String result = HttpRequest.post(authagreementUrl)
                            .connectTimeout(35000)
                            .readTimeout(35000)
                            .acceptJson()
                            .acceptCharset("UTF-8")
                            .send(jsonObject.toJSONString())
                            .body();
                    System.out.println("sssssss" + result);
                    JSONObject json = new JSONObject(result);
                    String resultCode = json.optString("resultCode");
                    msg = json.optString("resultDesc");
                    if(TextUtils.equals(resultCode, "CCOM1000")){
                        return null;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                return msg;
            }

            @Override
            protected void onPostExecute(String msg) {
                super.onPostExecute(msg);
                loadingView.dismiss();

                if(TextUtils.isEmpty(msg)){

                    AppCacheUtils.getInstance(activity).put(isAuthTimeKey, System.currentTimeMillis());

                    dismiss();
                } else {
                    Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
                }
            }
        };
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1) {
            task.execute();
        } else {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    }
}
